<?php

Const DATABASE_QUERY_TYPE_SELECT = "SELECT";
Const DATABASE_QUERY_TYPE_INSERT = "INSERT";
Const DATABASE_QUERY_TYPE_UPDATE = "UPDATE";


class baseModel {
    public $Debug;
	private $lrDBHandler;

	public function __construct() {
		$this->connect();
        $this->Debug = new systemDebug(TRUE, "database.txt");
	}

	public function connect() {
        global $_config;
        try {
            $this->lrDBHandler = new PDO($_config["connection"]["dbtype"].":host=".$_config["connection"]["host"].";dbname=".$_config["connection"]["database"], $_config["connection"]["username"], $_config["connection"]["password"]);
            $this->lrDBHandler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        } catch (Exception $e) {
            die("Critical error: Unable to connect to database");
        }
	}

	public function SimpleQuery($isSQL, $isQueryType = DATABASE_QUERY_TYPE_SELECT) {
        $lrResult = $this->lrDBHandler->query($isSQL);
        if(($isQueryType == DATABASE_QUERY_TYPE_SELECT) && $lrResult) {
		  return $lrResult->fetchAll();
        }
	}
        
    public function AdvancedQuery($isSQL, $irAttributes, $isQueryType = DATABASE_QUERY_TYPE_SELECT) {
        $lrReturn = null;
        //
        $lrQuery = $this->lrDBHandler->prepare($isSQL);
        $lrResult = $lrQuery->execute($irAttributes);
        //
        if(($isQueryType == DATABASE_QUERY_TYPE_SELECT) && $lrResult) {
            //return $lrResult->fetchAll();
            $lrReturn = $lrQuery->fetch(PDO::FETCH_ASSOC);
        }
        elseif(($isQueryType == DATABASE_QUERY_TYPE_INSERT) && $lrResult) {
            $lrReturn = $this->lrDBHandler->lastInsertId();
        }
        return $lrReturn;
    }

	public function RowCount($isSQL) {
		$lrQuery = $this->lrDBHandler->prepare($isSQL);
		$lrQuery->execute();
		return $lrQuery->rowCount();
	}

	public function __destruct() {
		$this->lrDBHandler = null;
	}

	public function getList($isTable) {
		return $this->SimpleQuery("SELECT * FROM ".$isTable);
	}

}
